package base;

import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.game.LayerManager;
import javax.microedition.lcdui.game.Sprite;



public class RotatableObject implements SpriteContainer {

	static double TAN_15 = 0.26794919243112270647255365849413;
	static double TAN_45 = 1;
	static double TAN_75 = 3.7320508075688772935274463415059;

	protected RotatableSprite sprite;
	protected double rotation = 0;
	public Sprite getSprite(){
		return sprite;
	}
	public void update()
	{
		
	}
	public int getX()
	{
		return sprite.getRefPixelX();
	}
	public int getY()
	{
		return sprite.getRefPixelY();
	}
	public void setPosition(int x,int y)
	{
		sprite.setRefPixelPosition(x, y);
		updatePositon();
	}
	public void move(int x,int y){
		sprite.move(x, y);
		updatePositon();
	}
	public void setRotation(double r)
	{
		rotation = r;
		sprite.setRotation(r);
		updatePositon();
	}
	public double getRotation()
	{
		return rotation;
	}
	public boolean isHover(int x,int y)
	{
		return x>sprite.getX()
				&&y>sprite.getY()
				&&x<sprite.getX()+sprite.getWidth()
				&&y<sprite.getY()+sprite.getHeight();
	}
	public void addTo(LayerManager layer)
	{
		layer.insert(sprite, layer.getSize()-1);
	}
	public void removeFrom(LayerManager layer)
	{
		layer.remove(sprite);
	}
	
	public double dist(int x0,int y0,int x1,int y1){
		return Math.sqrt((x1-x0)*(x1-x0)+(y1-y0)*(y1-y0));
	}
	public double dist(int x,int y){
		return dist(getX(), getY(), x, y);
	}
	public double arc(int x, int y) {
		double xn, yn, arc;
		if (x >= 0 && y < 0) {
			xn = -y;
			yn = x;
			arc = 0;
		} else if (x >= 0 && y >= 0) {
			xn = x;
			yn = y;
			arc = 90;
		} else if (x < 0 && y >= 0) {
			xn = y;
			yn = -x;
			arc = 180;
		} else {
			xn = -x;
			yn = -y;
			arc = 270;
		}
		if (yn == 0) {
			return arc;
		}
		double tan = (double)yn / xn;
		if (tan > TAN_75) {
			arc += 90;
		} else if (tan > TAN_45) {
			arc += 60;
		} else if (tan > TAN_15) {
			arc += 30;
		}
		if(arc>=360)
		{
			arc-=360;
		}
		return arc;
	}
	protected void updatePositon()
	{

	}
	public boolean moveTo(int x, int y,double sp) {
		double dx = x-getX();
		double dy = y-getY();
		
		//double sp = (double)speed/10;
		double d = dist(x, y);
		if(d<sp){
			setPosition(x, y);
			return true;
		}
		else{
			move((int)(dx*sp/d+0.5), (int)(dy*sp/d+0.5));
			return false;
		}
		// Math.
	}
	public void paint(Graphics g){
		sprite.paint(g);
	}
}
